package com.example.utils.http;

import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 模拟GET/POST方式
 * @author lit
 *
 */
public class HttpsUtils {

	/**
	 * post请求
	 * @param url 请求地址
	 * @param paramStr 参数
	 * @param charset 编码
	 * @return 返回值
	 */
	public static String doPost(String url, String paramStr, String charset) {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			httpClient = HttpClientBuilder.create().build();
			httpPost = new HttpPost(url);
			httpPost.addHeader("Content-Type", "application/json");
			StringEntity se = new StringEntity(paramStr, charset);
			se.setContentType("text/json");
			se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
			httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
	/**
	 * get请求
	 * @param url 请求地址
	 * @param charset 编码
	 * @return 返回值
	 */
	public static String doGet(String url, String charset) {
		HttpClient httpClient = null;
		HttpGet httpGet = null;
		String result = null;
		try {
			httpClient = HttpClientBuilder.create().build();
			httpGet = new HttpGet(url);
			httpGet.addHeader("Content-Type", "application/json");
			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
	
	/**
	 * get请求 大华 车辆管理专用的 获取车辆管理token值
	 * @param url 请求地址
	 * @param charset 编码
	 * @return 返回值
	 * @throws Exception 
	 */
	public static String doGetNoHeader(String url, String charset) throws Exception {
		CloseableHttpClient httpClient = createSSLClientDefault("");
		HttpUriRequest request = RequestBuilder.get()
				.setUri(url)
				.build();
		
		CloseableHttpResponse response = null;
		System.out.println(request.getRequestLine());
		response = httpClient.execute(request);
		if(response.getStatusLine().getStatusCode() == 200) {
			return EntityUtils.toString(response.getEntity(),"utf-8");
		}
		return response.getStatusLine().getStatusCode()+",调用接口异常";
	}
	/**
	 * get请求 大华 车辆管理专用的 header:token值
	 * @param url 请求地址
	 * @param charset 编码
	 * @return 返回值
	 * @throws Exception 
	 */
	public static String doGetSetHeader(String url, String charset,String header) throws Exception {
		CloseableHttpClient httpClient = createSSLClientDefault("");
		URIBuilder builder = new URIBuilder(url);
		URI uri = builder.build();
		HttpGet httpGet = new HttpGet(uri);
//		httpGet.addHeader("accessToken",header);
		HttpUriRequest request = RequestBuilder.get()
				.setUri(url)
				.setHeader("accessToken",header)
				.build();
		
		CloseableHttpResponse response = null;
		if(header == null || "".equals(header)) {
			response = httpClient.execute(httpGet);
		} else {
			System.out.println(request.getRequestLine());
			response = httpClient.execute(request);
		}
		if(response.getStatusLine().getStatusCode() == 200) {
			return EntityUtils.toString(response.getEntity(),"utf-8");
		}
		return response.getStatusLine().getStatusCode()+",调用接口异常";
	}
	
	
	 public static CloseableHttpClient createSSLClientDefault(String header) {
	        try {
	            //使用 loadTrustMaterial() 方法实现一个信任策略，信任所有证书
	            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
	                // 信任所有
	                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	                    return true;
	                }
	            }).build();
	            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
	            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
	            if(header == null || "".equals(header)) {
	            	return HttpClients.custom().setSSLSocketFactory(sslsf).build();
	            }else {
	            	List<BasicHeader> headers = Arrays.asList(new BasicHeader("X-Default-Header", "default header httpclient"));
	            	return HttpClients.custom().setDefaultHeaders(headers).setSSLSocketFactory(sslsf).build();
				}
	            
	        } catch (KeyManagementException e) {
	            e.printStackTrace();
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        } catch (KeyStoreException e) {
	            e.printStackTrace();
	        }
	        return HttpClients.createDefault();
	    }
	 
	public static void main(String[] args) {
		String token = "";
		String url = "http://10.0.200.196:80/ipms/subSystem/generate/token?userName=system";
		try {
			token = doGetSetHeader(url, "utf-8", "");
			Map<String, Object> map = new HashMap<String, Object>();
			System.out.println(token);
			map = JSONObject.parseObject(token);
			String dataJson = map.get("data").toString();
			map = JSONObject.parseObject(dataJson);
			token = map.get("accessToken").toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
//		System.out.println("token:"+token);
//		String url2 = "https://10.0.200.196:80/ipms/car/list";
//		try {
//			String msg = doGetSetHeader(url2, "utf-8", token);
//			System.out.println(msg);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
        
	}
}
